extends Node
var base = null
var utils = null
var dock = null
var layertxt
var net
var illustrate
var illustrate2
var jiban
var relic
var achieve
var server
var research

signal resetData
signal initMainUI
signal onBattleReady
signal onLoadGame
signal onNewGame
func _init():
	call_deferred("azurlineInit")
	print("碧蓝航线海军总部:已就绪")

#额外人口天赋
var addiPop:int = 0
#当前Up角色
var upCha = null
#当前Up角色名称
var upChaName = "无"
#当前是否已经抽到UP角色
var hadUp = false
#天赋：大力搜刮
var dalisougua = 1

func azurlineInit():
	if globalData.infoDs.has("g_azurlaneBase"):
		base = globalData.infoDs["g_azurlaneBase"]
	if base != null:
		#初始化
		base.connect("onLoadGame",self,"loadGame")
		base.connect("onNewGame",self,"newGame")
		base.connect("backTitle",self,"backTitle")
		base.connect("onSaveGame",self,"onSaveGame")
		utils = globalData.infoDs["g_azurlaneUtils"]
		dock = globalData.infoDs["g_azurlaneDock"]
		jiban = globalData.infoDs["g_azurlaneJiban"]
		relic = globalData.infoDs["g_azurlaneRelic"]
		achieve = globalData.infoDs["g_azurlaneAchieve"]
		illustrate = globalData.infoDs["g_azurlaneIllustrate"]
		illustrate2 = globalData.infoDs["g_azurlaneIllustrateCamp"]
		research = globalData.infoDs["g_azurlaneResearch"]
		server = globalData.infoDs["g_azurlaneServer"]
		net = load("%s/azurlane_ctrl/Net.gd" % [chaData.infoDs["cex___azurtoolman"].dir]).new()
		sys.add_child(net)
		# OS.window_maximized = true

func backTitle():
	resetData()

func onSaveGame():
	var tmp = {}

	tmp["mf"] = mf
	tmp["buli"] = buli
	tmp["upCha"] = upCha.id
	tmp["upChaName"] = upChaName
	base.setData("azurCtrl", tmp)

	saveChas()

func loadGame():
	base.setSetting("loadGame", true)
	resetData()
	loadData()
	gameCtrl()
	yield(sys.get_tree().create_timer(0.5), "timeout")
	emit_signal("onLoadGame")

func loadData():
	var tmp = base.getData("azurCtrl", {})
	if not tmp.empty():
		mf = tmp["mf"]
		buli = tmp["buli"]

		upCha = chaData.infoDs[tmp["upCha"]]
		upChaName = tmp["upChaName"]
	loadChas()

func saveChas():
	var chas = []
	for i in sys.main.map.get_children():
		if i is Chara and i.team == 1 and not i.isSumm:chas.append(i)
	if chas.empty():
		chas = utils.getAllChas(2)
		if chas.empty():
			print("警告：自动存档时没有检测到场上存在角色")
	chas += utils.getReadyChas()
	var savedChas = []
	for i in chas:
		if i.type == sys.CharaClass.NPC:
			i.removeAllEquip()
		savedChas.append(i.toJson())

	base.setData("chas", savedChas)
	saveItems(chas)

func saveItems(chas):
	var itemDic = {}
	var chaItemDic = {}
	for i in chas:
		for j in i.items:
			if i.get("rndId") != null:
				itemDic[j] = i.rndId
			if not chaItemDic.has(i.rndId):
				chaItemDic[i.rndId] = []
			chaItemDic.get(i.rndId).append(j.toJson())

	var items = []
	for i in sys.main.itemGrid.get_children():
		if i.item == null or itemDic.has(i.item):continue
		items.append(i.item.toJson())
	base.setData("items", items)
	base.setData("chaItems", chaItemDic)

func loadChas():
	var chasData = base.getData("chas", [])
	# #删除所有角色
	var chas = utils.getAllChas(2)
	chas += utils.getReadyChas()
	var index = chas.size() - 1
	while index >= 0:
		chas[index].deleteSelf()
		index -= 1

	var chaDic = {}
	for i in chasData:
		var cha = sys.main.newChara(i.id, 1)
		if i.has("cell"):
			sys.main.map.add_child(cha)
			cha.isDrag = true
			cha.isItem = false
		else:
			sys.main.player.addCha(cha)
		cha.fromJson(i)
		chaDic[cha.rndId] = cha
	loadItems(chaDic)

func loadItems(chaDic):
	#删除所有装备
	for i in sys.main.itemGrid.get_children():
		i.queue_free()

	var items = base.getData("items", [])
	var chaItems = base.getData("chaItems", {})
	for i in items:
		var im = sys.newItem(i.id)
		im.fromJson(i)
		sys.main.player.addItem(im)
	
	for i in chaItems.keys():
		if chaDic.has(int(i)):
			var cha = chaDic.get(int(i))
			for j in chaItems.get(i):
				var im = sys.newItem(j.id)
				im.fromJson(j)
				sys.main.player.addItem(im)
				cha.addItem(im)

func resetData():
	mf = 0
	mfLb = null
	buliLb = null
	buli = 0
	addiPop = 0
	emit_signal("resetData")

func newGame():
	resetData()
	base.setSetting("loadGame", false)
	gameCtrl()
	startChoiceChara()
	if sys.test:
		changeMF(0)
	changeBuli(4)
	yield(sys.get_tree().create_timer(0.3), "timeout")
	emit_signal("onNewGame")

func gameCtrl():
	uiCtrl()

	sys.main.connect("onBattleReady", self, "onBattleReady")
	sys.main.connect("onBattleEnd", self, "onBattleEnd")
	sys.main.connect("onBattleStart",self,"onBattleStart")

func onBattleReady():
	#所有G文件的onBattleReady应由此统一管理，以免产生乱序问题
	# if sys.main.player.maxHp < 400:
	# 	sys.main.player.maxHp += 100
	# sys.main.player.plusHp(200)
	emit_signal("onBattleReady")
			
func onBattleEnd():	
	pass

func onBattleStart():
	statis1 = {}
	statis2 = {}

func uiCtrl():
	battleUI()
	
func battleUI():
	#战斗背景
	var uiNode = sys.main.get_node("ui")
	sys.main.get_node("scene/bg/bg").set_texture(base.loadImg(sys.getBasePath(), "g_azurlane/bg_normal.png"))
	layertxt = utils.createRichTextLabel("当前层数:%d" % (sys.main.guankaMsg.lvStep - 2), uiNode, Vector2(950, 50), Vector2(400, 0))
	layertxt.push_align(1)
	#控制面板
	createSettingPanel()

	var hbox = utils.createVBox(uiNode, Vector2(1300, 0))
	hbox.name = "azurBtnBox"
	utils.createItemButton(hbox, dock, "港区船坞(Q)", "open", [], Vector2(0, 0), KEY_Q)
	utils.createItemButton(hbox, self, "控制面板(W)", "setting", [], Vector2(0, 0), KEY_W)
	utils.createItemButton(hbox, research, "科研系统(E)", "show", [], Vector2(0, 0), KEY_E)
	buildBattleStatis()
	loadResourceUI()

	emit_signal("initMainUI")

	var hbox2 = utils.createHBox(uiNode, Vector2(1200, 620))
	hbox2.name = "btnBoxRB"
	utils.createItemButton(hbox2, jiban, "当前羁绊(T)", "show", [], Vector2(1300, 600), KEY_T)
	# utils.createItemButton(hbox2, self, "舰队属性(I)", "fleetInfo", [], Vector2(1300, 600), KEY_I)

#舰队属性
func fleetInfo():
	if sys.main.get_node("ui").has_node("fleetInfo") and is_instance_valid(sys.main.get_node("ui/fleetInfo")):
		sys.main.get_node("ui/fleetInfo").queue_free()
	var panel = utils.createWindowDialog(sys.main.get_node("ui"), "舰队属性", Vector2(600, 500))
	panel.name = "fleetInfo"
	panel.popup_centered()

	var cost = 0
	var chas = sys.main.getAllChas(2)
	for i in chas:
		cost += i.cost

	if chas.empty():return
	var text = "[color=#BDB76B]总消耗:[/color] [color=#DC143C]%d[/color] 魔方"%[int(cost)]
	utils.createRichTextLabel(text, panel, Vector2(500, 400), Vector2(50, 50))

# func refreshCost():
	# if sys.main.isAiStart:return
	# var cost = 0
	# var chas = sys.main.getAllChas(2)
	# for i in chas:
	# 	cost += i.cost
	# costLb.bbcode_text = "舰队消耗:[color=#DC143C]%d[/color]"%[cost]
	
#开局四选一
func startChoiceChara():
	var window = utils.createWindowDialog(sys.main.get_node("ui"), "初始舰娘", Vector2(800, 400))
	window.popup_exclusive = true
	window.get_close_button().hide()

	utils.createRichTextLabel("请选择你的初始舰娘", window, Vector2(200, 50), Vector2(30, 30))
	var grid = utils.createGridContainer(window, 5, Vector2(50, 100))
	utils.newChaBt(grid, "biaoqiang-4")
	utils.newChaBt(grid, "lafei-4")
	utils.newChaBt(grid, "lingbo-4")
	utils.newChaBt(grid, "z23-4")
	utils.newChaBt(grid, "kaixuan-4")

	utils.createItemButton(grid, self, "选择", "doChoiceChara", ["biaoqiang-1", window])
	utils.createItemButton(grid, self, "选择", "doChoiceChara", ["lafei-1", window])
	utils.createItemButton(grid, self, "选择", "doChoiceChara", ["lingbo-1", window])
	utils.createItemButton(grid, self, "选择", "doChoiceChara", ["z23-1", window])
	utils.createItemButton(grid, self, "选择", "doChoiceChara", ["kaixuan-1", window])

	window.popup_centered()

func doChoiceChara(id, window):
	sys.main.player.addCha(utils.newChara(id))
	window.queue_free()
	if jinJieData.nowLv == 0:
		relic.open()

func createSettingPanel():
	var settingPanel = utils.createWindowDialog(sys.main.get_node("ui"), "碧蓝航线控制面板", Vector2(600, 300))
	settingPanel.name = "setting"

	var gridList = utils.createGridContainer(settingPanel, 4, Vector2(80, 50))

	utils.createItemButton(gridList, self, "切换背景", "switchBG", [])
	utils.createItemButton(gridList, self, "MOD说明", "guide", [])
	utils.createItemButton(gridList, illustrate, "角色图鉴", "openIllstrate", [])
	utils.createItemButton(gridList, illustrate2, "阵营图鉴", "openIllstrate", [])
	utils.createItemButton(gridList, relic, "当前遗物", "showRecord", [])
	utils.createItemButton(gridList, self, "更新日志", "changeLog", [])
	utils.createItemButton(gridList, achieve, "成就系统", "open", [])
	utils.createItemButton(gridList, server, "排行榜", "rankList", [])
	

func setting():
	sys.main.get_node("ui/setting").popup_centered()

var bg = ["g_azurlane/bg_normal.png", "g_azurlane/bg_normal2.png"]
#切换背景
func switchBG():
	var bgIndex = base.getSetting("bgPic", 0)
	bgIndex += 1
	if bgIndex > bg.size()-1:
		bgIndex = 0
	base.setSetting("bgPic", bgIndex)
	sys.main.get_node("scene/bg/bg").set_texture(base.loadImg(sys.getBasePath(), bg[bgIndex]))

func loadResourceUI():
	var grid = utils.createGridContainer(sys.main.get_node("ui"), 2)
	grid.rect_position = Vector2(1430, 310)

	grid.add_child(utils.createTextureRect("icons/bulis.png"))
	buliLb = utils.createRichTextLabel("布里:[color=#DC143C]%d"%buli, grid, Vector2(120, 40))

	grid.add_child(utils.createTextureRect("icons/mofang.png"))
	mfLb = utils.createRichTextLabel("魔方:[color=#DC143C]%d"%mf, grid, Vector2(120, 40))

	# costLb = utils.createRichTextLabel("舰队消耗:[color=#DC143C]%d[/color]"%[0], sys.main.get_node("ui"), Vector2(120, 40), Vector2(1420, 210))

#MOD说明
func guide():
	OS.shell_open(utils.consts.helpUrl)

#更新日志
func changeLog():
	utils.openHelpWindow(utils.readChangeLog())

#===============================================战斗统计相关===============================================
var statis1 = {}
var statis2 = {}
func getDefaultStatis(cha):
	return {"damage":0, "hurt":0, "deal":0, "team":cha.team, "name":cha.chaName, "cha":cha, "kill":0}
var statisContainer
var statisWindow
func battleStatis():
	loadStatis(1)
	var timeLabel = statisWindow.get_node("time")
	timeLabel.bbcode_text = "战斗时间：%d"%[sys.main.battleTime]
	statisWindow.popup_centered()
func buildBattleStatis():
	statisWindow = utils.createWindowDialog(sys.main.get_node("ui"), "战斗统计", Vector2(1000, 600))

	utils.createItemButton(statisWindow, self, "我方", "loadStatis", [1], Vector2(50, 20))
	utils.createItemButton(statisWindow, self, "敌方", "loadStatis", [2], Vector2(105, 20))

	var timeLabel = utils.createRichTextLabel("战斗时间：%d"%[sys.main.battleTime], statisWindow, Vector2(150, 50), Vector2(190, 30))
	timeLabel.name = "time"

	var statisScroll = utils.createScrollContainer(statisWindow, Vector2(950, 480), Vector2(30, 100))
	statisContainer = utils.createVBox(statisScroll)

	var dpsBtn = sys.main.get_node("ui/dps/dpsBtn")
	dpsBtn.text = "战斗统计"
	# dpsBtn.connect("pressed", self, "battleStatis")
	utils.addShotCutToBtn(dpsBtn, KEY_S)

func loadStatis(team = 1):
	for i in statisContainer.get_children():
		i.queue_free()
	var statis
	if team == 1:
		statis = statis1
	else:
		statis = statis2
	var values = statis.values()
	values.sort_custom(self, "sortStatis")

	var grid = utils.createGridContainer(statisContainer, 6)
	for i in values:
		utils.createRichTextLabel("{0}".format({"0":i.name}), grid, Vector2(280, 50))
		utils.createRichTextLabel("[color=#FFA500]伤害{1}[/color]".format({"1":int(i.damage)}), grid, Vector2(160, 50))
		utils.createRichTextLabel("[color=#FF0000]承伤{2}[/color]".format({"2":int(i.hurt)}), grid, Vector2(160, 50))
		utils.createRichTextLabel("[color=#008000]治疗{3}[/color]".format({"3":int(i.deal)}), grid, Vector2(160, 50))
		utils.createRichTextLabel("[color=#F8F8FF]击杀{3}[/color]".format({"3":int(i.kill)}), grid, Vector2(100, 50))
		utils.createItemButton(grid, self, "详情", "battleDetail", [i.cha])

func sortStatis(a, b):
	return a.damage > b.damage

func getStatisByCha(cha):
	var statis
	if cha.team == 1:
		statis = statis1.get(cha, getDefaultStatis(cha))
	else:
		statis = statis2.get(cha, getDefaultStatis(cha))
	return statis

func setStatisByCha(cha, statis):
	if cha.isSumm:return
	if cha.team == 1:
		statis1[cha] = statis
	else:
		statis2[cha] = statis

func battleDetail(cha):
	cha.battleDetail(cha, statisContainer)

#获得伤害最高的角色:1友军2敌军
func getChaByDmg(team = 1):
	var values = statis1.values()
	if team == 2:
		values = statis2.values()
	values.sort_custom(self, "sortStatis")
	for i in values:
		if not i.cha.isDeath:
			return i.cha
	return null

##########################资源相关#################################

var mfLb = null
var buliLb = null
# var costLb = null
#布里
var buli = 0
#魔方
var mf = 0

func changeMF(num):
	mf += num
	mfLb.bbcode_text = "魔方:[color=#DC143C]%d"%int(mf)

func changeBuli(num):
	buli += num
	buliLb.bbcode_text = "布里:[color=#DC143C]%d"%int(buli)

#检查额外人口
func checkPop():
	return addiPop

func changeUpCha():
	#当前Up
	if sys.main.getStep() % 4 == 0 or upCha == null:
		var up = sys.rndListItem(chaData.upChas)
		while upCha != null and up.id == upCha.id:
			up = sys.rndListItem(chaData.upChas)
		upCha = up
		upChaName = up.name
		hadUp = false

func refreshTopLb():
	if layertxt != null:
		var text = "当前层数：%d" % (sys.main.getStep())

		if upChaName != null:
			text += "    当前UP：%s"%upChaName

		layertxt.bbcode_text = text